@file:JvmName("NetUtils")

package org.jash.shop2202.utils

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.jash.shop2202.BuildConfig
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

private val client by lazy {
    OkHttpClient.Builder()
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .connectTimeout(30, TimeUnit.SECONDS)
        .callTimeout(30, TimeUnit.SECONDS)
        .addInterceptor { chain ->
//            chain.proceed(StoreUtils.getUtils().getString("token", "")
//                .takeIf { it.isNotEmpty() }
//                ?.let { chain.request().newBuilder().addHeader("token", it).build() } ?: chain.request())
            val token = StoreUtils.getUtils().getString("token", "")
            val request = if(token.isNotEmpty())
                chain.request().newBuilder().addHeader("token", token).build()
            else
                chain.request()
            chain.proceed(request)
        }
        .apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            }
        }
        .build()
}

val retrofit by lazy {
    Retrofit.Builder()
        .baseUrl("http://10.161.9.80:7012/")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

inline fun <reified T> getService() = retrofit.create(T::class.java)